<template>
     <el-form :inline="true" :model="form" label-width="auto" style="padding: 10px;">
        <el-form-item label="名称">
          <el-input v-model="form.name"/>
        </el-form-item>
       <el-form-item label="触发方式">
         <el-select v-model="form.triggerType" placeholder="触发方式" :disabled="openByBusiness">
           <el-option  v-for="item in dict.sceneTrigger" :label="item.label" :value="item.value" :key="item.value"/>
         </el-select>
       </el-form-item>
       <template v-if="form.triggerType==='TERMINAL'">
         <el-form-item label="终端类型">
           <el-select v-model="form.profileCode" filterable remote
                      placeholder="---请选择---"
                      :remote-method="(w)=>queryProfileOptions(w,null,null,formOptions.profile)"
                      @change="(val)=>{
                        const item = formOptions.profile.data.filter((v)=>{return v.value === val})[0]
                        form.signal = form.terminalCode = '';
                        //formOptions.signal.data=item.ext;
                        formOptions.terminal.data=[];
                      }"
                      :loading="loading"
                      :disabled="openByBusiness">
             <el-option v-for="item1 in formOptions.profile.data" :key="item1.value" :label="item1.label" :value="item1.value"/>
           </el-select>
         </el-form-item>
<!--         <el-form-item label="遥测信号">-->
<!--           <el-select v-model="form.signal" placeholder="-&#45;&#45;请选择-&#45;&#45;">-->
<!--             <el-option v-for="item in formOptions.signal.data" :key="item.value" :label="item.label" :value="item.value"/>-->
<!--           </el-select>-->
<!--         </el-form-item>-->
         <el-form-item label="触发终端">
           <el-select v-model="form.terminalCode" filterable remote reserve-keyword
                      placeholder="---请选择---"
                      :remote-method="(w)=>queryTerminalOptions(w,null,form.profileCode,formOptions.terminal)"
                      :loading="loading"
                      :disabled="openByBusiness">
             <el-option v-for="item in formOptions.terminal.data" :key="item.value" :label="item.label" :value="item.value"/>
           </el-select>
         </el-form-item>
       </template>
       <el-form-item label="触发表达式">
         <el-input v-model="form.triggerExpress"/>
       </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark"  style="width: 700px;"/>
        </el-form-item>

       <div>
         <el-form-item label="触发时段">
           <el-switch v-model="form.planEnable" style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ccc"/>
         </el-form-item>
         <el-form-item label="告警">
           <el-switch v-model="form.alarmEnable" style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ccc"/>
         </el-form-item>

         <el-form-item label="联动">
           <el-switch v-model="form.actionEnable" style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ccc"/>
         </el-form-item>
       </div>
         <template v-if="form.planEnable">
           <week-plan v-model="form.plan"/>
         </template>
       <template v-if="form.alarmEnable">
         <el-form-item label="告警条件">
           <el-select v-model="form.alarmSetting.triggerMode" placeholder="告警条件" style="width: 100px;">
             <el-option v-for="item in dict.alarmPolicy" :label="item.label" :value="item.value" :key="item.value"/>
           </el-select>
           <el-input v-model="form.alarmSetting.triggerValue" style="width: 50px;"/>
         </el-form-item>

         <el-form-item label="详细信息">
           <el-input v-model="form.alarmSetting.detail" style="width: 600px;"/>
         </el-form-item>
         <div>
         <el-form-item label="告警清除">
           <el-switch v-model="form.alarmSetting.autoClear" style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ccc"/>
         </el-form-item>
         </div>
         <template v-if="form.alarmSetting.autoClear">
           <el-form-item label="清除表达式" v-if="form.alarmSetting.autoClear">
             <el-input v-model="form.alarmSetting.clearExpress"/>
           </el-form-item>
           <el-form-item label="清除条件" >
             <el-select v-model="form.alarmSetting.clearMode" placeholder="告警策略" style="width: 100px;">
               <el-option  v-for="item in dict.alarmPolicy" :label="item.label" :value="item.value" :key="item.value"/>
             </el-select>
             <el-input v-model="form.alarmSetting.clearValue" style="width: 50px;"/>
           </el-form-item>
         </template>

       </template>

       <template v-if="form.actionEnable">
         <div style="display: flex;align-items: center;margin-bottom: 20px; border-bottom: 1px #ccc solid">
         <el-radio-group v-model="tabIndex" size="large" @change="handleChangeTab">
           <el-radio-button v-for="(item,key) in form.actionFlow" :label="key">{{`动作${key+1}`}}</el-radio-button>
         </el-radio-group>
           <div class="flex-grow" />
           <el-button @click="handleTabsEdit('add')">添加</el-button>
           <el-button  @click="handleTabsEdit('remove')">删除</el-button>
         </div>
  <!--             <el-form-item label="执行条件">-->
  <!--               <el-input v-model="getActionFlow(curTab).conditionExpress" style="width: 700px;"/>-->
  <!--             </el-form-item>-->
         <el-container>
           <el-aside width="230px" direction="vertical" style="border-right: 1px #ccc solid;">
             <slot name="default">
               <el-row class="header">
                 <el-col :span="18">
                   执行动作
                 </el-col>
                 <el-col :span="6">
                   <el-button icon="Plus" type="primary" link  @click="handleAddAction()" style="width: 20px;margin:0;"/>
                   <el-button icon="Minus" type="danger" link  @click="handleRemoveAction()" style="width: 20px;margin:0;"/>
                 </el-col>
               </el-row>
             </slot>
             <el-table :data="getActionFlow(curTab).actions"
                       :show-header="false"
                       highlight-current-row
                       :empty-text="'没有数据'"
                       :stripe="false"
                       :row-key="row => row.name"
                       :current-row-key="getActionFlow(curTab).actions[curActionIndex].name"
                       @current-change="handleActionCurrentChange">
               <el-table-column prop="name" label="名称"/>
             </el-table>
           </el-aside>
           <el-main>
             <div style="padding: 0 0 0 10px">
               <el-form-item label="动作名称">
                 <el-input v-model="getActionFlow(curTab).actions[curActionIndex].name"/>
               </el-form-item>
               <el-form-item label="动作类型">
                 <el-select v-model="getActionFlow(curTab).actions[curActionIndex].actionType" placeholder="动作类型">
                   <el-option  v-for="item in dict.sceneAction" :label="item.label" :value="item.value" :key="item.value"/>
                 </el-select>
               </el-form-item>

               <el-form-item label="终端类型">
                 <el-select v-model="getActionFlow(curTab).actions[curActionIndex].profileCode" filterable remote
                            placeholder="---请选择---"
                            :remote-method="(w)=>queryProfileOptions(w,null,null,getFormOptions(curTab,curActionIndex).profile)"
                            @change="handleProfileChange"
                            :loading="loading">
                   <el-option v-for="item in getFormOptions(curTab,curActionIndex).profile.data" :key="item.value" :label="item.label" :value="item.value"/>
                 </el-select>
               </el-form-item>
               <el-form-item label="执行终端">
                 <el-select v-model="getActionFlow(curTab).actions[curActionIndex].terminalCode" filterable remote reserve-keyword
                            placeholder="---请选择---"
                            :remote-method="(w)=>queryTerminalOptions(w,null,getActionFlow(curTab).actions[curActionIndex].profileCode,getFormOptions(curTab,curActionIndex).terminal)"
                            :loading="loading">
                   <el-option v-for="item in getFormOptions(curTab,curActionIndex).terminal.data" :key="item.value" :label="item.label" :value="item.value"/>
                 </el-select>
               </el-form-item>
               <el-form-item label="延迟">
                 <el-input v-model="getActionFlow(curTab).actions[curActionIndex].delay"/>
               </el-form-item>
               <el-form-item label="内容">
                 <!--getActionFlow(curTab).actions[curActionIndex].params-->
                 <cmeditor ref="codeEditor" v-model="getActionFlow(curTab).actions[curActionIndex][`params`]" :width="440"></cmeditor>
               </el-form-item>
             </div>
           </el-main>
         </el-container>
       </template>

          <div style="text-align:center;margin: 10px auto;">
            <el-button type="primary" @click="handleAdd">保存</el-button>
            <el-button @click="handleCancel">取消</el-button>
          </div>
      </el-form>
</template>
<script>
    import{reactive, ref} from 'vue'
    import {add,edit} from '/http/scene.js'
    import cmeditor from "../../component/cmeditor.vue";
    import {useDict,searchTable} from '/http/options.js'
    import signal from "../signal/index.vue";
    import WeekPlan from "../../component/weekPlan.vue";
    const {ElTable} = ElementPlus;
    export default {
      computed: {
        signal() {
          return signal
        }
      },
      components: {WeekPlan, cmeditor},
        props:{
          initParams:Object
        },
        setup(props,context){
          const loading = ref(false);
          const dict = ref({});
          const codeEditor = ref(null)
          const tabIndex = ref(0);
          const openByBusiness = ref(false);

          const formOptions = ref({
            profile:{data:[]},
            terminal:{data:[]},
            //signal:{data:[]},
            actions:[[{
              profile:{data:[]},
              terminal:{data:[]}
            }]]
          });

          const getFormOptions=(i1,i2)=>{
            if(!formOptions.value.actions[i1]){
              formOptions.value.actions[i1]=[];
            }
            if(!formOptions.value.actions[i1][i2]){
              formOptions.value.actions[i1][i2]={
                profile:{data:[]},
                terminal:{data:[]}
              };
            }
            return formOptions.value.actions[i1][i2];
          }

          const getActionFlow=(i1)=>{
            if(!form.actionFlow[i1]){
              form.actionFlow[i1] = JSON.parse(JSON.stringify(actionFlowTpl));
            }
            return form.actionFlow[i1];
          }

          useDict(dict,'sceneAction,sceneTrigger,alarmPolicy');



          const actionTpl = {
            name:'执行1',
            actionType:'',
            profileCode:'',
            terminalCode:'',
            delay:0,
            params:''
          }

          const actionFlowTpl = {
            //conditionExpress:'value>1',
            actions:[actionTpl]
          }
          const form=reactive({
            id:'',
            name:'',
            remark:'',
            triggerType:'TERMINAL',
            triggerExpress:'',
            profileCode:'',
            terminalCode:'',
            gatewayCode:'',
            signal:'',
            actionEnable:false,
            alarmEnable:false,
            planEnable:false,
            plan:[],
            alarmSetting:{
              triggerMode:'CONTINUOS',
              triggerValue:1,
              detail:'',
              autoClear:false,
              clearExpress:'',
              clearMode:'CONTINUOS',
              clearValue:1
            },
            actionFlow:[JSON.parse(JSON.stringify(actionFlowTpl))]
          })


          const handleAdd = ()=>{
              if(action.value=='add'){
                add(form).then(res=> {
                  response(res,context)
                });
              }else{
                edit(form).then(res=> {
                  response(res,context)
                });
              }
          }


          const handleCancel = ()=>{
              context.emit('close',false)
          }
          const action = ref('edit');
          const dialog = ref(null);


          const handleClose1 = (data)=>{
            data.forEach(item=>{
              form.signalList.push(item);
            })
          }




          function onSelectSignal(){
            dialog.value.open(form.signalList);
          }
          const curTab = ref(0)
          const curActionIndex = ref(0);
          onMounted(()=>{
            if(props.initParams){
              openByBusiness.value = !!props.initParams.openByBusiness
              Object.assign(form,props.initParams)
              if(form.id){
                action.value= 'edit'
              }else{
                action.value= 'add'
              }


              queryProfileOptions(null,form.profileCode,null,formOptions.value.profile,(data)=>{
                //formOptions.value.signal.data = data[0].ext
              })
              queryTerminalOptions(null,form.terminalCode,null,formOptions.value.terminal)
              form.actionFlow.forEach((flow,flowIndex)=>{
                flow.actions.forEach((action,actionIndex)=>{
                  queryProfileOptions(null,action.profileCode,null,getFormOptions(flowIndex,actionIndex).profile)
                  queryTerminalOptions(null,action.terminalCode,null,getFormOptions(flowIndex,actionIndex).terminal)
                })
              })
            }else{
              action.value= 'add'
            }
          })

          //添加或删除动作
          const handleTabsEdit = (action) => {
            if (action === 'add') {
              form.actionFlow.push(JSON.parse(JSON.stringify(actionFlowTpl)))
              curTab.value = form.actionFlow.length-1
            } else if (action === 'remove') {
              form.actionFlow.splice(curTab.value, 1);
              const max = form.actionFlow.length-1;
              if(curTab.value>max){
                curTab.value = max
              }
            }
            curActionIndex.value =0;
          }

          //查询终端类型
          const queryProfileOptions = (w,id,pid,options,callback)=>{
            loading.value = true
            searchTable('profile',{w,id,pid}).then(res=>{
              options.data = res.data;
              loading.value = false
              if(callback){
                callback(options.data);
              }
            })
          }
          //查询终端
          const queryTerminalOptions = (w,id,pid,options,callback)=>{
            loading.value = true
            searchTable('terminal',{w,id,pid:pid}).then(res=>{
              options.data = res.data;
              loading.value = false
              if(callback){
                callback(options.data);
              }
            })
          }

          //切换tab
          const handleChangeTab = (val)=>{
            curActionIndex.value = 0;
            curTab.value = val;
          }

          //新增执行
          const handleAddAction = (val) => {
            let num = 1;
            getActionFlow(curTab.value).actions.forEach(item=>{
              const lastNumber = item.name.match(/\d+$/);
              const tempNum = lastNumber ? parseInt(lastNumber[0], 10) : 1;
              if(tempNum>num){
                num =tempNum;
              }
              num+=1;
            })
            const action = JSON.parse(JSON.stringify(actionTpl))
            action.name = '执行'+num;
            getActionFlow(curTab.value).actions.push(action);

          }

          //删除执行
          const handleRemoveAction=()=>{
            getActionFlow(curTab.value).actions.splice(curActionIndex.value,1)
            const maxIndex = getActionFlow(curTab.value).actions.length-1;
            if(curActionIndex.value>maxIndex){
              curActionIndex.value = maxIndex;
            }
          }

          //切换执行
          const handleActionCurrentChange = (val) => {
            curActionIndex.value = form.actionFlow[curTab.value].actions.findIndex(item=>{return item===val})
          }

          return{
            form,handleAdd,handleCancel,action,dialog,
            onSelectSignal,handleClose1,dict,handleTabsEdit,
            curTab,handleActionCurrentChange,handleAddAction,
            queryProfileOptions,queryTerminalOptions,formOptions,
            curActionIndex,getFormOptions,handleChangeTab,getActionFlow,codeEditor,
            handleRemoveAction,tabIndex,openByBusiness
          }
        }
    }
</script>

<style scoped>
.el-form .el-select {
  width: 160px; /* 或者根据需要设置其他宽度 */
}
.el-form .el-input {
  width: 160px; /* 或者根据需要设置其他宽度 */
}
.vertical-radio .el-radio {
  display: block;
  margin: 0 0 10px 0; /* 可根据需要调整间距 */
}
.header {
  height: 50px;
  font-weight: bold;
  border-top: #f0f0f0 solid 1px;
  background-color: #f0f0f0;
  box-shadow: 2px 2px 4px rgba(0,0,0,0.1);
  margin-bottom: 10px;

}
.header .el-col{
  display:flex;align-items: center; padding-left: 10px;
}
.flex-grow {
  flex-grow: 1;
}
</style>